package com.ruoyi.web.controller.stask;

import com.ruoyi.cat.domain.*;
import com.ruoyi.cat.domain.DTO.ArticletaskDTO;
import com.ruoyi.cat.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 计划任务服务 - 负责处理文章和活动的收益分配
 */
@Slf4j
@RestController
@RequestMapping("/api/scheduleTask1")
@Component
public class ScheduledTask {

    @Autowired
    private ICatIprecordTableService ipRecordService;

    @Autowired
    private ICatActivityTableService activityService;

    @Autowired
    private ICatArticletaskTableService articleTaskService;

    @Autowired
    private ICatBasedataTableService baseDataService;

    @Autowired
    private ICatUserbasicTableService userService;

    @Autowired
    private ICatTradedetailTableService tradeDetailService;

    /**
     * 每天凌晨1点执行，计算用户分享收益
     */
  //  @Scheduled(cron = "0 0 1 * * ?")
    public void calculateShareRewards() {
        log.info("开始执行分享收益计算任务");
        try {
            // 获取系统基础配置
            CatBasedataTable baseData = baseDataService.selectCatBasedataTableByIdRedis(1L);
            if (baseData == null) {
                log.error("未找到系统基础配置数据");
                return;
            }

            // 获取昨日的分享记录数据
            List<CatIprecordTable> shareRecords = ipRecordService.getShareUserId();
            if (CollectionUtils.isEmpty(shareRecords)) {
                log.info("没有需要处理的分享记录");
                return;
            }

            // 处理每条分享记录
            AtomicInteger successCount = new AtomicInteger(0);
            for (CatIprecordTable record : shareRecords) {
                try {
                    // 根据类型分别处理文章和活动
                    if ("1".equals(record.getType())) {
                        processArticleReward(record, baseData);
                    } else {
                        processActivityReward(record, baseData);
                    }
                    successCount.incrementAndGet();
                } catch (Exception ex) {
                    log.error("处理用户收益失败，用户ID：{}，记录类型：{}", record.getShareUserId(), record.getType(), ex);
                }
            }
            log.info("分享收益计算任务完成，成功处理{}条记录", successCount.get());
        } catch (Exception e) {
            log.error("分享收益计算任务执行异常", e);
        }
    }

    /**
     * 手动触发文章分享收益计算测试（单条记录）
     */
    @GetMapping("/getTask1")
    public void testSingleArticleReward() {
        CatIprecordTable testRecord = new CatIprecordTable();
        testRecord.setShareUserId(122L);
        testRecord.setType("2");
        testRecord.setArticleId(25L);

        CatBasedataTable baseData = baseDataService.selectCatBasedataTableByIdRedis(1L);
        if (baseData == null) {
            log.error("未找到系统基础配置数据");
            return;
        }

        processActivityReward(testRecord, baseData);
        log.info("测试文章收益计算完成");
    }

    /**
     * 手动触发所有分享收益计算
     */
    @GetMapping("/getTask")
    public void manualTriggerRewardCalculation() {
        calculateShareRewards();
    }

    /**
     * 处理活动分享收益
     *
     * @param record 分享记录
     * @param baseData 系统基础配置
     */
    private void processActivityReward(CatIprecordTable record, CatBasedataTable baseData) {
        // 获取活动信息
        CatActivityTable activity = activityService.selectCatActivityTableByIdTask(record.getArticleId());
        if (activity == null) {
            log.warn("活动不存在，活动ID：{}", record.getArticleId());
            return;
        }

        // 获取分享用户信息
        CatUserbasicTable sharer = userService.selectCatUserbasicTableById(record.getShareUserId());
        if (sharer == null) {
            log.warn("用户不存在，用户ID：{}", record.getShareUserId());
            return;
        }

        // 注意：活动不区分省内省外IP，获取总访问量
        // 获取用户分享的总UV数量
        Long totalUvCount = getTotalUvCount(record);
        Long totalUvXx = getTotalUvCountX(record);
        getTotalUvCountTj(record);
        if (totalUvCount == 0) {
            log.info("活动没有访问量，跳过处理，活动ID: {}, 用户ID: {}", activity.getId(), sharer.getId());
            return;
        }

        // 1. 个人产生的UV总数 * 活动基础成本
        BigDecimal activityBaseCost = activity.getActivityBaseCost();
        BigDecimal offsiteDiscountRate = baseData.getAreaReward(); // 分成比例
        BigDecimal introduceReward = baseData.getIntroduceReward(); // 推荐奖励比例

        BigDecimal personalReward = BigDecimal.valueOf(totalUvCount)
                .multiply(activityBaseCost)
                .setScale(2, RoundingMode.HALF_UP);

        log.info("用户[ID:{}]活动[ID:{}]个人产生收益：{}", sharer.getId(), activity.getId(), personalReward);

        // 计算推荐人关系和下线关系
        boolean hasReferrer = sharer.getReferenceId() != null && sharer.getReferenceId() > 0;
        boolean hasDownline = hasDownlineUsers(sharer.getId());

        // 计算最终收益
        BigDecimal finalReward = personalReward; // 默认最终收益等于个人产生收益
        BigDecimal rewardToReferrer = BigDecimal.ZERO; // 给上线的收益

        // 情况1：有上线 - 需要给上线分一部分收益
        if (hasReferrer) {
            // 检查上线是否分享了该活动
            boolean referrerSharedActivity = checkReferrerSharedContent(sharer.getReferenceId(), activity.getId(), "2");
            if (referrerSharedActivity) {
                // 活动团队助力: 下线产生的UV总数 * 分成比例 * 活动基础成本
                rewardToReferrer = BigDecimal.valueOf(totalUvXx)
                        .multiply(offsiteDiscountRate)
                        .multiply(activityBaseCost)
                        .setScale(2, RoundingMode.HALF_UP);

                // 给上线记录收益
                if (rewardToReferrer.compareTo(BigDecimal.ZERO) > 0) {
                    log.info("用户[ID:{}]活动[ID:{}]给上线[ID:{}]收益：{}",
                            sharer.getId(), activity.getId(), sharer.getReferenceId(), rewardToReferrer);

                    // 获取上线用户对象
                    CatUserbasicTable referrer = userService.selectCatUserbasicTableById(sharer.getReferenceId());
                    if (referrer != null) {
                        // 团队助力人数 = 下线UV数 * 推荐奖励比例 (四舍五入取整)
                        long helpingPeople = Math.round(totalUvXx * introduceReward.doubleValue());

                        recordTradeDetail(
                                referrer,
                                activity.getId(),
                                sharer.getReferenceId(),
                                rewardToReferrer,
                                sharer.getId(),
                                "0",
                                helpingPeople,
                                "活动团队助力收益",
                                "2"
                        );
                    }
                }

                // 个人收益减去给上线的部分
                finalReward = personalReward.subtract(rewardToReferrer);
            }
        }

        // 情况2：有下线 - 下线的贡献会在下线处理时计入当前用户
        // 下线收益在各自处理时已经计算并记录，这里不需要额外处理

        // 记录最终个人收益(个人产生 - 给上线的)
        if (finalReward.compareTo(BigDecimal.ZERO) > 0) {
            log.info("用户[ID:{}]活动[ID:{}]最终收益：{}", sharer.getId(), activity.getId(), finalReward);
            recordTradeDetail(
                    sharer,
                    activity.getId(),
                    sharer.getId(),
                    finalReward,
                    null,
                    "0",
                    totalUvCount,
                    "活动个人收益",
                    "2"
            );
        }
    }

    /**
     * 检查用户是否有下线
     * @param record
     * @return
     */
    private Long getTotalUvCountX(CatIprecordTable record) {
        List<CatUserbasicTable> list =  userService.countByReferenceData(record.getShareUserId());
        // 初始化累加器
        long totalCount = 0;
        for (CatUserbasicTable e : list) {
            // 临时保存原始的 shareUserId
            Long originalShareUserId = record.getShareUserId();
            record.setShareUserId(e.getId());
            Long count =  ipRecordService.countShareRecord(record);
            if (count != null) {
                totalCount += count;
            }
            // 恢复原始的 shareUserId
            record.setShareUserId(originalShareUserId);
        }
        return totalCount;
    }

    private List<CatUserbasicTable> getTotalUvCountTj(CatIprecordTable record) {
        List<CatUserbasicTable> list =  userService.countByReferenceData(record.getShareUserId());

        return list;
    }

    /**
     * 获取用户分享的总UV数量
     */
    private Long getTotalUvCount(CatIprecordTable record) {
        // 活动不区分省内省外，直接获取总UV
        CatIprecordTable uvCountRecord = ipRecordService.getTotalUvCount(record);
        return uvCountRecord != null ? uvCountRecord.getQuantity() : 0L;
    }

    /**
     * 检查推荐人是否分享过该活动
     */
    private boolean checkReferrerSharedActivity(Long referrerId, Long activityId) {
        CatIprecordTable query = new CatIprecordTable();
        query.setShareUserId(referrerId);
        query.setArticleId(activityId);
        query.setType("2"); // 活动类型

        return ipRecordService.existsShareRecord(query);
    }

    /**
     * 处理文章分享收益
     *
     * @param record 分享记录
     * @param baseData 系统基础配置
     */
    private void processArticleReward(CatIprecordTable record, CatBasedataTable baseData) {
        // 获取文章信息
        ArticletaskDTO article = articleTaskService.selectCatArticletaskById(record.getArticleId());
        if (article == null) {
            log.warn("文章不存在，文章ID：{}", record.getArticleId());
            return;
        }

        // 获取分享用户信息
        CatUserbasicTable sharer = userService.selectCatUserbasicTableById(record.getShareUserId());
        if (sharer == null) {
            log.warn("用户不存在，用户ID：{}", record.getShareUserId());
            return;
        }

        // 获取系统参数
        BigDecimal baseProfit = baseData.getBaseProfit();
        BigDecimal baseCost = baseData.getBaseCost();
        BigDecimal offsiteDiscountRate = baseData.getAreaReward();
        BigDecimal introduceReward = baseData.getIntroduceReward(); // 推荐奖励比例
        Long targetNum = article.getTargetNum();

        // 设置文章所在区域，获取本地和异地访问数据
        record.setAreaValue(article.getCity());
        CatIprecordTable localRecord = ipRecordService.getStaskData(record);
        CatIprecordTable remoteRecord = ipRecordService.getStaskDataNo(record);

        // 初始化本地和异地访问量
        Long localQuantity = (localRecord != null) ? localRecord.getQuantity() : 0L;
        Long remoteQuantity = (remoteRecord != null) ? remoteRecord.getQuantity() : 0L;
        Long totalQuantity = localQuantity + remoteQuantity;

        if (totalQuantity == 0) {
            log.info("文章没有访问量，跳过处理，文章ID: {}, 用户ID: {}", article.getId(), sharer.getId());
            return;
        }

        // 计算本地收益
        BigDecimal localAmount = calculateLocalAmount(baseCost, targetNum, baseProfit, localQuantity);

        // 计算异地收益
        BigDecimal remoteAmount = calculateRemoteAmount(baseCost, targetNum, baseProfit, offsiteDiscountRate, remoteQuantity);

        // 计算最终收益
        BigDecimal totalReward = calculateTotalReward(sharer, localAmount, remoteAmount, introduceReward,
                article.getId(), record.getShareUserId(), totalQuantity);

        // 记录文章分享收益
        recordTradeDetail(sharer, article.getId(), record.getShareUserId(), totalReward,
                null, "0", totalQuantity, "文章分享收益", "1");

        // 计算并记录平台奖励（文章达标奖励）
        calculatePlatformReward(sharer, baseCost, targetNum, baseProfit, offsiteDiscountRate,
                localQuantity, remoteQuantity, article.getId(), record.getShareUserId());
    }

    /**
     * 计算最终用户收益（考虑推荐关系）
     */
    private BigDecimal calculateTotalReward(CatUserbasicTable user, BigDecimal localAmount,
                                            BigDecimal remoteAmount, BigDecimal introduceReward,
                                            Long articleId, Long shareUserId, Long totalViews) {
        CatIprecordTable catIprecordTable = new CatIprecordTable();
        catIprecordTable.setShareUserId(shareUserId);
        catIprecordTable.setArticleId(articleId);
        catIprecordTable.setType("1");
        Long totalUvXx = getTotalUvCountX(catIprecordTable);
        // 初始化收益为本地+异地收益总和
        BigDecimal totalReward = localAmount.add(remoteAmount);
        BigDecimal userReward = totalReward;

        // 检查是否有推荐人和下线
        boolean hasReferrer = user.getReferenceId() != null && user.getReferenceId() > 0;
        boolean hasDownline = hasDownlineUsers(user.getId());

        if (hasReferrer) {
            // 检查推荐人是否也分享了这篇文章
            boolean referrerSharedArticle = checkReferrerSharedContent(user.getReferenceId(), articleId, "1");
            if (referrerSharedArticle) {
                // 转化收益: 异地收益 * IntroduceReward
                BigDecimal referrerReward = remoteAmount.multiply(introduceReward)
                        .setScale(2, RoundingMode.HALF_UP);

                if (referrerReward.compareTo(BigDecimal.ZERO) > 0) {
                    // 获取上线用户
                    CatUserbasicTable referrer = userService.selectCatUserbasicTableById(user.getReferenceId());
                    if (referrer != null) {
                        // 文章团队助力人数 = 下线IP总合 * IntroduceReward（四舍五入取整数）
                        long helpingPeople = Math.round(totalUvXx * introduceReward.doubleValue());

                        // 记录给上线的收益
                        recordTradeDetail(
                                referrer,
                                articleId,
                                user.getReferenceId(),
                                referrerReward,
                                shareUserId,
                                "0",
                                helpingPeople,
                                "文章团队助力收益",
                                "1"
                        );

                        log.info("用户[ID:{}]给上线[ID:{}]文章[ID:{}]转化收益：{}，助力人数：{}",
                                shareUserId, user.getReferenceId(), articleId, referrerReward, helpingPeople);
                    }
                }

                // 用户收益减去推荐人收益
                userReward = totalReward.subtract(referrerReward);
            }
        }

        // 返回最终用户收益，确保不低于0
        return userReward.max(BigDecimal.ZERO);
    }

    /**
     * 计算平台奖励（文章达标奖励）
     */
    private void calculatePlatformReward(CatUserbasicTable user, BigDecimal baseCost, Long targetNum,
                                         BigDecimal baseProfit, BigDecimal offsiteDiscountRate,
                                         Long localIpCount, Long remoteIpCount, Long articleId, Long shareUserId) {
        // 计算有效基础成本（减去基础利润后的总成本）
        BigDecimal effectiveBaseCost = baseCost
                .multiply(BigDecimal.valueOf(targetNum))
                .multiply(BigDecimal.ONE.subtract(baseProfit));

        // 计算本地和异地扣除
        BigDecimal deductionLocal = effectiveBaseCost
                .divide(BigDecimal.valueOf(10000), 10, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(localIpCount));

        BigDecimal deductionOffsite = effectiveBaseCost
                .divide(BigDecimal.valueOf(10000), 10, RoundingMode.HALF_UP)
                .multiply(offsiteDiscountRate)
                .multiply(BigDecimal.valueOf(remoteIpCount));

        // 计算最终平台奖励
        BigDecimal platformReward = effectiveBaseCost.subtract(deductionLocal).subtract(deductionOffsite);

        if (platformReward.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 如果奖励为零或负数，不记录
        }

        // 更新用户余额并记录交易
        updateUserBalance(user, platformReward);
        recordTradeDetail(user, articleId, shareUserId, platformReward,
                null, "2", 0L, "文章推广收益", "1");
    }

    /**
     * 计算本地收益
     */
    private BigDecimal calculateLocalAmount(BigDecimal baseCost, Long targetNum,
                                            BigDecimal baseProfit, Long quantity) {
        if (targetNum == null || targetNum == 0 || quantity == null || quantity == 0) {
            return BigDecimal.ZERO;
        }

        return baseCost
                .multiply(BigDecimal.valueOf(targetNum))
                .multiply(BigDecimal.ONE.subtract(baseProfit))
                .divide(BigDecimal.valueOf(targetNum), 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(quantity))
                .max(BigDecimal.ZERO);
    }

    /**
     * 计算异地收益
     */
    private BigDecimal calculateRemoteAmount(BigDecimal baseCost, Long targetNum, BigDecimal baseProfit,
                                             BigDecimal offsiteDiscountRate, Long quantity) {
        if (targetNum == null || targetNum == 0 || quantity == null || quantity == 0) {
            return BigDecimal.ZERO;
        }

        return baseCost
                .multiply(BigDecimal.valueOf(targetNum))
                .multiply(BigDecimal.ONE.subtract(baseProfit))
                .divide(BigDecimal.valueOf(targetNum), 2, RoundingMode.HALF_UP)
                .multiply(offsiteDiscountRate)
                .multiply(BigDecimal.valueOf(quantity))
                .max(BigDecimal.ZERO);
    }

    /**
     * 每天凌晨2点执行, 处理冻结资金释放
     */
    //@Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 2 * * ?")
    @GetMapping("/getTask5")
    public void releaseFreezeFunds() {
        log.info("开始执行冻结资金释放任务");
        try {
            // 处理文章任务
            processArticleTasks();
            // 处理活动任务
            processActivityTasks();
            log.info("冻结资金释放任务完成");
        } catch (Exception e) {
            log.error("冻结资金释放任务执行失败", e);
            throw new RuntimeException("冻结资金释放任务执行失败", e);
        }
    }

    @GetMapping("/getTask4")
    @Scheduled(cron = "0 0 * * * ?") // 同步修改第二个任务的cron
    public void releaseFreezeFunds1() {
        List<CatArticletaskTable> list = articleTaskService.getTimeData();
        for (CatArticletaskTable article : list) {
            article.setArticleExamine("3");
            articleTaskService.updateVisitors(article);
        }

        List<CatActivityTable> list1 = activityService.getActivityDataTime();
        for (CatActivityTable article : list1) {
            article.setArticleExamine("3");
            activityService.updateCatActivity(article);
        }
    }

    /**
     * 处理文章任务资金释放
     */
    private void processArticleTasks() {
        List<CatArticletaskTable> articles = articleTaskService.getArticletaskTask();
        if (CollectionUtils.isEmpty(articles)) {
            log.info("没有需要处理的文章任务");
            return;
        }

        log.info("开始处理{}个文章任务的冻结资金", articles.size());
        int successCount = 0;

        for (CatArticletaskTable article : articles) {
            try {
                // 处理该文章相关的所有交易明细
                int count = processTradeDetails(article.getId(), "1");

                // 更新文章状态为已结算(3)
              //  article.setArticleExamine("3");
               // articleTaskService.updateCatArticletaskTable(article);

                successCount++;
                log.info("文章任务[ID:{}]处理完成，释放{}笔交易", article.getId(), count);
            } catch (Exception e) {
                log.error("处理文章任务失败，任务ID：{}", article.getId(), e);
            }
        }

        log.info("文章任务处理完成，成功处理{}个文章", successCount);
    }

    /**
     * 处理活动任务资金释放
     */
    private void processActivityTasks() {
        List<CatActivityTable> activities = activityService.getActivityTaskTask();
        if (CollectionUtils.isEmpty(activities)) {
            log.info("没有需要处理的活动任务");
            return;
        }

        log.info("开始处理{}个活动任务的冻结资金", activities.size());
        int successCount = 0;

        for (CatActivityTable activity : activities) {
            try {
                // 处理该活动相关的所有交易明细
                int count = processTradeDetails(activity.getId(), "2");

                // 更新活动状态为已结算(3)
              //  activity.setArticleExamine("3");
               // activityService.updateCatActivity(activity);

                successCount++;
                log.info("活动任务[ID:{}]处理完成，释放{}笔交易", activity.getId(), count);
            } catch (Exception e) {
                log.error("处理活动任务失败，活动ID：{}", activity.getId(), e);
            }
        }

        log.info("活动任务处理完成，成功处理{}个活动", successCount);
    }

    /**
     * 处理交易明细，将冻结资金转为可用资金
     *
     * @param activityId 活动/文章ID
     * @param type 类型：1-文章 2-活动
     * @return 处理的交易笔数
     */
    @Transactional(rollbackFor = Exception.class)
    public int processTradeDetails(Long activityId, String type) {
        // 查询待处理的交易明细
        CatTradedetailTable queryParam = new CatTradedetailTable();
        queryParam.setActivityId(activityId);
        queryParam.setStatusType("0"); // 未结算
        queryParam.setType(type);

        List<CatTradedetailTable> tradeDetails = tradeDetailService.getTaskJF(queryParam);

        if (CollectionUtils.isEmpty(tradeDetails)) {
            return 0;
        }

        int successCount = 0;
        for (CatTradedetailTable trade : tradeDetails) {
            try {
                releaseUserFrozenFunds(trade,activityId);
                successCount++;
            } catch (Exception e) {
                log.error("释放用户冻结资金失败，用户ID：{}，交易ID：{}", trade.getId(), e);
                throw e; // 抛出异常触发事务回滚
            }
        }

        return successCount;
    }

    /**
     * 释放用户冻结资金，转为可用余额
     */
    private void releaseUserFrozenFunds(CatTradedetailTable trade,Long activityId) {
        CatUserbasicTable user = userService.selectCatUserbasicTableById(trade.getUserId());
        if (user == null) {
            log.warn("用户不存在，用户ID：{}", trade.getUserId());
            return;
        }

        // 计算新的冻结金额和可用金额
        BigDecimal tradeAmount = trade.getTradeNum();

        // 处理冻结金额为null的情况
        BigDecimal freezeDeposits = user.getFreezeDeposits() != null ? user.getFreezeDeposits() : BigDecimal.ZERO;

        // 确保冻结金额不会变为负数
        BigDecimal newFreezeDeposits = freezeDeposits.subtract(tradeAmount).max(BigDecimal.ZERO);

        // 处理余额为null的情况
        BigDecimal currentAmount = user.getAmount() != null ? user.getAmount() : BigDecimal.ZERO;
        BigDecimal newAmount = currentAmount.add(tradeAmount);

        // 更新用户余额
        user.setFreezeDeposits(newFreezeDeposits);
        user.setAmount(newAmount);

        // 乐观锁更新
        int result = userService.updateCatUserbasicTable(user);
        if (result != 1) {
            throw new RuntimeException("更新用户余额失败，可能发生并发更新，用户ID：" + user.getId());
        }

        // 更新交易状态
        trade.setStatusType("1"); // 已结算
        trade.setActivityId(activityId);
        tradeDetailService.updateCatTradedetailAndUserId(trade);

        log.info("用户[ID:{}]冻结资金释放成功，金额：{}", user.getId(), tradeAmount);
    }

    /**
     * 更新用户冻结余额
     */
    private void updateUserBalance(CatUserbasicTable user, BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不处理
        }

        // 处理冻结金额为null的情况
        BigDecimal freezeDeposits = user.getFreezeDeposits() != null ? user.getFreezeDeposits() : BigDecimal.ZERO;
        user.setFreezeDeposits(freezeDeposits.add(amount));

        int result = userService.updateCatUserbasicTable(user);
        if (result != 1) {
            log.warn("更新用户冻结余额失败，用户ID：{}", user.getId());
        }
    }

    /**
     * 记录交易明细
     */
    private void recordTradeDetail(CatUserbasicTable user, Long activityId, Long userId,
                                   BigDecimal amount, Long profitUserId, String income,
                                   Long helpingPeople, String tradeTitle, String type) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不记录
        }

        CatTradedetailTable tradeDetail = new CatTradedetailTable();
        tradeDetail.setActivityId(activityId);
        tradeDetail.setUserId(userId);
        tradeDetail.setTradeType("0"); // 收入
        tradeDetail.setTradeTitle(tradeTitle);
        tradeDetail.setTradeNum(amount);
        tradeDetail.setType(type);
        tradeDetail.setProfitUserId(profitUserId);
        tradeDetail.setIncome(income);
        tradeDetail.setHelpingPeople(helpingPeople);

        // 插入交易记录
        tradeDetailService.insertCatTradedetailTable(tradeDetail);

        // 更新用户冻结余额
        updateUserBalance(user, amount);

        log.info("记录交易明细成功：用户ID={}，活动ID={}，金额={}，类型={}",
                userId, activityId, amount, type);
    }

    /**
     * 检查推荐人是否分享过该文章/活动
     *
     * @param referrerId 推荐人ID
     * @param contentId 文章/活动ID
     * @param type 类型（1-文章，2-活动）
     * @return 是否分享过
     */
    private boolean checkReferrerSharedContent(Long referrerId, Long contentId, String type) {
        CatIprecordTable query = new CatIprecordTable();
        query.setShareUserId(referrerId);
        query.setArticleId(contentId);
        query.setType(type);
        return ipRecordService.existsShareRecord(query);
    }

    /**
     * 检查用户是否有下线用户
     */
    private boolean hasDownlineUsers(Long userId) {
        return userService.countByReferenceId(userId) > 0;
    }
}